import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:play_lab/constants/my_strings.dart';
import 'package:play_lab/core/route/route.dart';
import 'package:play_lab/core/utils/dimensions.dart';
import 'package:play_lab/core/utils/my_color.dart';
import 'package:play_lab/core/utils/my_icons.dart';
import 'package:play_lab/core/utils/my_images.dart';
import 'package:play_lab/core/utils/styles.dart';
import 'package:play_lab/core/utils/url_container.dart';
import 'package:play_lab/data/controller/my_menu/my_menu_controller.dart';
import 'package:play_lab/data/repo/account/profile_repo.dart';
import 'package:play_lab/data/services/api_service.dart';
import 'package:play_lab/view/components/bottom_Nav/bottom_nav.dart';
import 'package:play_lab/view/components/image/custom_svg_picture.dart';
import 'package:play_lab/view/components/image/my_image_widget.dart';
import 'package:play_lab/view/will_pop_widget.dart';

class MenuScreen extends StatefulWidget {
  const MenuScreen({super.key});

  @override
  State<MenuScreen> createState() => _MenuScreenState();
}

class _MenuScreenState extends State<MenuScreen> {
  final List<MenuBar> accountsMenus = [
    MenuBar(
      title: MyStrings.profileSetting,
      route: RouteHelper.profileScreen,
      icon: Icons.settings,
    ),
    if (!Get.find<ApiClient>().isSocialUser()) ...[
      MenuBar(
        title: MyStrings.changePassword,
        route: RouteHelper.changePasswordScreen,
        icon: Icons.key_outlined,
        isMenuEnable: !Get.find<ApiClient>().isSocialUser(),
      ),
    ],
  ];
  final List<MenuBar> paymentMenus = [
    MenuBar(
      title: MyStrings.subscription,
      route: RouteHelper.subscribeScreen,
      icon: Icons.subscriptions_outlined,
    ),
    MenuBar(
      title: MyStrings.payment,
      route: RouteHelper.paymentHistoryScreen,
      icon: Icons.payment,
    ),
  ];
  final List<MenuBar> watchMenus = [
    if (Get.find<ApiClient>().isWatchPartyEnable()) ...[
      MenuBar(
        title: MyStrings.watchParty,
        route: RouteHelper.watchPartyHistoryScreen,
        icon: Icons.history,
        iconImage: MyImages.watchPartyImage,
        isImage: true,
      ),
    ],
    MenuBar(
      title: MyStrings.rentedItems,
      route: RouteHelper.rentItemScreen,
      icon: Icons.subscriptions_outlined,
      iconImage: MyImages.sideNameRentImage,
      isImage: true,
    ),
    if (Get.find<ApiClient>().isGeneReEnable()) ...[
      MenuBar(
        title: MyStrings.genres,
        route: RouteHelper.genreScreen,
        icon: Icons.subscriptions_outlined,
        iconImage: MyImages.sideNameRentImage,
        isImage: true,
      ),
    ],
    MenuBar(
      title: MyStrings.wishList,
      route: RouteHelper.wishListScreen,
      icon: Icons.favorite_outline,
    ),
    MenuBar(
      title: MyStrings.history,
      route: RouteHelper.myWatchHistoryScreen,
      icon: Icons.history,
    ),
  ];
  final List<MenuBar> reelsNRequestMenus = [
    MenuBar(
      title: MyStrings.myReels,
      route: RouteHelper.myReelsVideoScreen,
      icon: Icons.play_arrow_rounded,
      iconImage: MyImages.sideNameRentImage,
      isImage: true,
    ),
    if (Get.find<ApiClient>().isRequestItemEnable()) ...[
      MenuBar(
        title: MyStrings.myRequest,
        route: RouteHelper.myRequestScreen,
        icon: Icons.history,
        iconImage: MyImages.watchPartyImage,
        isImage: true,
      ),
    ],
    if (Get.find<ApiClient>().isRequestItemEnable()) ...[
      MenuBar(
        title: MyStrings.allRequested,
        route: RouteHelper.allRequestScreen,
        icon: Icons.history,
        iconImage: MyImages.watchPartyImage,
        isImage: true,
      ),
    ],
  ];
  final List<MenuBar> othersMenus = [
    MenuBar(
      title: MyStrings.supportTicket,
      route: RouteHelper.allTicketScreen,
      icon: Icons.contact_support_outlined,
    ),
    MenuBar(
      title: MyStrings.policies,
      route: RouteHelper.privacyScreen,
      icon: Icons.favorite_outline,
      iconImage: MyImages.privacyIcon,
      isSvg: true,
    ),
    MenuBar(
      title: MyStrings.faq,
      route: RouteHelper.faqScreen,
      icon: Icons.favorite_outline,
      iconImage: MyIcons.faq,
      isSvg: true,
    ),
    MenuBar(
      title: MyStrings.language,
      route: RouteHelper.languageScreen,
      icon: Icons.language,
    ),
  ];

  @override
  void initState() {
    Get.put(ProfileRepo(apiClient: Get.find()));
    final controller = Get.put(MyMenuController(repo: Get.find()));
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((t) {
      controller.getProfileInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(statusBarColor: MyColor.cardBg),
      child: WillPopWidget(
        child: GetBuilder<MyMenuController>(builder: (controller) {
          return Scaffold(
            backgroundColor: MyColor.colorBlack,
            bottomNavigationBar: const CustomBottomNav(currentIndex: 4),
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(120),
              child: OverflowBox(
                maxHeight: 100,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: Dimensions.space10, vertical: Dimensions.space10),
                  // margin: EdgeInsets.symmetric(horizontal: Dimensions.space10),
                  decoration: BoxDecoration(
                    color: MyColor.cardBg,
                    borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: Row(
                          spacing: Dimensions.space15,
                          children: [
                            InkWell(
                              onTap: () => Get.toNamed(RouteHelper.profileScreen),
                              child: Container(
                                height: 62,
                                width: 62,
                                decoration: BoxDecoration(color: MyColor.colorWhite, shape: BoxShape.circle),
                                child: MyImageWidget(
                                  imageUrl: '${UrlContainer.userProfileAssetPath}${controller.getUserImage()}',
                                  isProfile: true,
                                  height: 60,
                                  width: 60,
                                  radius: 50,
                                ),
                              ),
                            ),
                            Expanded(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                spacing: Dimensions.space5,
                                children: [
                                  Text(
                                    controller.getUserFullName(),
                                    style: boldDefault.copyWith(),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  Text(
                                    controller.getUserEmail(),
                                    style: mulishLight.copyWith(),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: Dimensions.space10, vertical: Dimensions.space5 - 1),
                        decoration: BoxDecoration(color: (controller.isPaidUser() ? MyColor.greenSuccessColor : MyColor.red).withValues(alpha: 0.1), borderRadius: BorderRadius.circular(Dimensions.space5)),
                        child: Text(
                          MyStrings.subscribed,
                          style: regularDefault.copyWith(
                            color: (controller.isPaidUser() ? MyColor.greenSuccessColor : MyColor.red),
                            decorationColor: MyColor.colorBlack,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            body: SafeArea(
              child: RefreshIndicator(
                backgroundColor: MyColor.primaryColor,
                color: MyColor.colorWhite,
                onRefresh: () async => controller.getProfileInfo(),
                child: ListView(
                  padding: Dimensions.screenPaddingHV,
                  children: [
                    Text(MyStrings.accounts.tr, style: mulishMedium.copyWith(color: MyColor.colorWhite)),
                    SizedBox(height: Dimensions.space10),
                    GenerateMenuList(menus: accountsMenus),
                    SizedBox(height: Dimensions.space20),
                    Text(MyStrings.videosNReels.tr, style: mulishMedium.copyWith(color: MyColor.colorWhite)),
                    SizedBox(height: Dimensions.space10),
                    GenerateMenuList(menus: watchMenus),
                    SizedBox(height: Dimensions.space20),
                    Text(MyStrings.payment.tr, style: mulishMedium.copyWith(color: MyColor.colorWhite)),
                    SizedBox(height: Dimensions.space10),
                    GenerateMenuList(menus: paymentMenus),
                    SizedBox(height: Dimensions.space20),
                    Text(MyStrings.reelsNRequest.tr, style: mulishMedium.copyWith(color: MyColor.colorWhite)),
                    SizedBox(height: Dimensions.space10),
                    GenerateMenuList(menus: reelsNRequestMenus),
                    SizedBox(height: Dimensions.space20),
                    Text(MyStrings.supportNFaq.tr, style: mulishMedium.copyWith(color: MyColor.colorWhite)),
                    SizedBox(height: Dimensions.space10),
                    GenerateMenuList(menus: othersMenus),
                    SizedBox(height: Dimensions.space20),
                    InkWell(
                      onTap: () => controller.logOutUser(),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: Dimensions.space15, vertical: Dimensions.space15),
                        decoration: BoxDecoration(
                          color: MyColor.cardBg,
                          borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              spacing: 10,
                              children: [
                                Icon(Icons.logout, color: MyColor.colorWhite),
                                Text(MyStrings.logout.tr, style: mulishMedium.copyWith()),
                              ],
                            ),
                            controller.isLogoutLoading ? SpinKitFadingCircle(color: MyColor.redCancelTextColor, size: Dimensions.fontExtraLarge + 3) : Icon(Icons.arrow_forward_ios_outlined, size: 16, color: MyColor.colorGrey3),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: Dimensions.space10),
                    InkWell(
                      onTap: () => controller.deleteAccount(),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: Dimensions.space15, vertical: Dimensions.space15),
                        decoration: BoxDecoration(
                          color: MyColor.redCancelTextColor,
                          borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              spacing: 10,
                              children: [
                                CustomSvgPicture(image: MyIcons.userNotEligibleIcon, color: MyColor.colorWhite),
                                Text(MyStrings.delete.tr, style: mulishMedium.copyWith()),
                              ],
                            ),
                            controller.isDeleteLoading ? SpinKitFadingCircle(color: MyColor.colorWhite, size: Dimensions.fontExtraLarge + 3) : Icon(Icons.arrow_forward_ios_outlined, size: 16, color: MyColor.colorGrey3),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: Dimensions.space20 * 2),
                  ],
                ),
              ),
            ),
          );
        }),
      ),
    );
  }
}

class GenerateMenuList extends StatelessWidget {
  const GenerateMenuList({super.key, required this.menus});

  final List<MenuBar> menus;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: Dimensions.space15, right: Dimensions.space15, top: Dimensions.space15, bottom: Dimensions.space5),
      decoration: BoxDecoration(
        color: MyColor.cardBg,
        borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
      ),
      child: Column(
        spacing: Dimensions.space15 + 1,
        children: List.generate(
          menus.length,
          (index) {
            final item = menus[index];
            return Visibility(
              visible: item.isMenuEnable,
              child: MenuBar(
                icon: item.icon,
                title: item.title,
                route: item.route,
                iconImage: item.iconImage,
                isImage: item.isImage,
                isMenuEnable: item.isMenuEnable,
                isSvg: item.isSvg,
                isShowDivider: index != menus.length - 1,
              ),
            );
          },
        ),
      ),
    );
  }
}

class MenuBar extends StatelessWidget {
  final String title, route;
  final IconData icon;
  final String? iconImage;
  final bool isImage, isMenuEnable;
  final bool isSvg, isShowDivider;
  final Function? onTap;

  const MenuBar({
    super.key,
    required this.title,
    required this.route,
    required this.icon,
    this.iconImage,
    this.onTap,
    this.isImage = false,
    this.isSvg = false,
    this.isMenuEnable = true,
    this.isShowDivider = true,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        InkWell(
          onTap: () => Get.toNamed(route),
          customBorder: CircleBorder(),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: Dimensions.space10, vertical: Dimensions.space10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  spacing: 10,
                  children: [
                    isSvg
                        ? CustomSvgPicture(image: iconImage!, height: 20, width: 20, color: MyColor.colorWhite)
                        : isImage
                            ? Image.asset(iconImage!, height: 20, width: 20, color: MyColor.colorWhite)
                            : Icon(icon, color: MyColor.colorWhite),
                    Text(title, style: mulishLight.copyWith()),
                  ],
                ),
                Icon(Icons.arrow_forward_ios_outlined, size: 16, color: MyColor.colorGrey3),
              ],
            ),
          ),
        ),
        isShowDivider ? Divider(color: MyColor.bodyTextColor, height: 0.5, thickness: 0.5) : SizedBox.shrink(),
      ],
    );
  }
}
